unit uFrmCageTournament;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, Grids, StdCtrls, uUtils, ExtCtrls, Buttons, gnugettext, uFrmPlayerWin, uSQLs, strutils,
  ImgList, uFrmDisplay, uMainUtils, shellapi, pngimage, ufrmloading, ufrmcanceloperation, ufrmplayerout,
  uImagePanel, ufrmdealerselect, uFrmSubjectImage, oracle, jpeg;

type
  TfrmCageTournament = class(TForm)
    Label3: TLabel;
    stg_Players: TStringGrid;
    Label4: TLabel;
    stg_Tournaments: TStringGrid;
    stg_TableOcupation: TStringGrid;
    Label1: TLabel;
    chb_ShowFromAllTables: TCheckBox;
    img_Player: TImage;
    btn_PlayerWinner: TSpeedButton;
    btn_PlayerOut: TSpeedButton;
    btn_CancelOperation: TSpeedButton;
    lbl_date: TLabel;
    lbl_time: TLabel;
    tmr_RefreshTime: TTimer;
    lbl_TournamentName: TLabel;
    ImageList1: TImageList;
    Label13: TLabel;
    pnl_Clock: TPanel;
    lbl_OutColor: TLabel;
    lbl_ToPayColor: TLabel;
    lbl_AddRebColor: TLabel;
    lbl_PaidColor: TLabel;
    dtp_Date: TDateTimePicker;
    Label2: TLabel;
    btn_Today: TButton;
    com_ShowFinished: TCheckBox;
    btn_ShowBigClock: TSpeedButton;
    btn_Reprint: TSpeedButton;
    btn_PauseContinue: TButton;
    img_Cashier: TImagePanel;
    img_Inspector: TImage;
    procedure dtp_DateChange(Sender: TObject);
    procedure btn_CancelOperationClick(Sender: TObject);
    procedure stg_TournamentsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure btn_PlayerWinnerClick(Sender: TObject);
    procedure stg_TableOcupationSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure chb_ShowFromAllTablesClick(Sender: TObject);
    procedure com_OrderTicketsByChange(Sender: TObject);
    procedure stg_PlayersSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure tmr_RefreshTimeTimer(Sender: TObject);
    procedure btn_PauseContinueClick(Sender: TObject);
    procedure chb_ShowOlderClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure stg_TournamentsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_PlayersDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_TableOcupationDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_PlayersDblClick(Sender: TObject);
    procedure stg_TournamentsDblClick(Sender: TObject);
    procedure btn_PlayerOutClick(Sender: TObject);
    procedure btn_TodayClick(Sender: TObject);
    procedure com_ShowFinishedClick(Sender: TObject);
    procedure btn_ShowBigClockClick(Sender: TObject);
    procedure btn_ReprintClick(Sender: TObject);
    procedure stg_TournamentsKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure img_CashierClick(Sender: TObject);
  private
    { Private declarations }
    CanSelect: Boolean;
    PrevTicketID, TableOccPrevRow: string;
    procedure GetTicketsData(TournamentId: string; TableId: string = '');
  public
    { Public declarations }
    TicketToPay, TicketToRebAdd: Boolean;
    SelectedTournamentId: Integer;
    m_FrmDisplay: TFrmDisplay;
    procedure GetLoggedCahiers();
  end;

var
  frmCageTournament: TfrmCageTournament;

const
  SelectedColor = clWhite;

implementation

uses uFrmMain, uFrmSellTicket;
{$R *.dfm}

procedure TfrmCageTournament.stg_PlayersDblClick(Sender: TObject);
var
  PlayerID, TableId: string;
begin
  if (stg_Tournaments.Row > 1) and (stg_Players.Cells[9, stg_Players.Row] = '') then // 8:player out time
  begin
    PlayerID := stg_Players.Cells[2, stg_Players.Row];
    TableId := stg_Players.Cells[12, stg_Players.Row];
    frm_SellTicket.ShowSellTicketForm('', stg_Tournaments.Cells[0, stg_Tournaments.Row], PlayerID, stg_Players.Cells[0, stg_Players.Row], '', stg_Players.Cells[13, stg_Players.Row],
      stg_Players.Cells[14, stg_Players.Row]);
    dtp_DateChange(self);
  end
  else if btn_PlayerWinner.Enabled and (stg_Players.Cells[10, stg_Players.Row] <> '') and (stg_Players.Cells[11, stg_Players.Row] = '') then
  begin
    btn_PlayerWinner.Click;
  end;
end;

procedure TfrmCageTournament.stg_PlayersDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  frmMain.GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TfrmCageTournament.stg_PlayersSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
  TicketID: string;
begin
  TicketID := stg_Players.Cells[0, ARow];
  if (TicketID <> '') then
  begin
    PrevTicketID := TicketID;
    if ARow > 1 then
    begin
      img_Player.Picture := uUtils.GetImage(SQL_Player_Picture + '(select player_id from tickets where id=' + TicketID + ')', frmMain.OracleSession1, True);
      img_Player.Repaint;
      if stg_Players.Cells[10, ARow] = '' then // WIN position
      BEGIN
        btn_PlayerOut.Enabled := True;
        btn_PlayerWinner.Enabled := false;
      END
      else
      begin
        btn_PlayerOut.Enabled := false;
        if (stg_Players.Cells[11, ARow] = '')and(stg_Tournaments.Cells[16, stg_Tournaments.Row] <> '') then // WIN value
        BEGIN
          if stg_Tournaments.Row > 1 then
          begin
            if StrToInt(stg_Players.Cells[10, ARow]) <= StrToInt(stg_Tournaments.Cells[16, stg_Tournaments.Row]) then
            begin
              btn_PlayerWinner.Enabled := True;
            end
            else
            begin
              btn_PlayerWinner.Enabled := false;
            end;
          end;
        END
        else
        begin
          btn_PlayerWinner.Enabled := false;
        end;
      end;
    end;
  end
  else if (TicketID <> PrevTicketID) then
  begin
    img_Player.Picture := nil;
    btn_PlayerOut.Enabled := false;
    btn_PlayerWinner.Enabled := false;
  end;
end;

procedure TfrmCageTournament.stg_TableOcupationDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  frmMain.GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TfrmCageTournament.stg_TableOcupationSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
  if (ARow > 1) and (stg_Tournaments.Row > 1) and (TableOccPrevRow <> IntToStr(ARow)) then
  begin
    TableOccPrevRow := IntToStr(ARow);
    GetTicketsData(stg_Tournaments.Cells[0, stg_Tournaments.Row], stg_TableOcupation.Cells[0, ARow]);
  end;
end;

procedure TfrmCageTournament.stg_TournamentsDblClick(Sender: TObject);
begin
  if stg_Tournaments.Cells[0, stg_Tournaments.Row] <> '' then
  begin
    frm_SellTicket.ShowSellTicketForm('', stg_Tournaments.Cells[0, stg_Tournaments.Row], '', '-1');
    dtp_DateChange(self);
  end;
end;

procedure TfrmCageTournament.stg_TournamentsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
  s: string;
begin
  frmMain.GridDrawCell(Sender, ACol, ARow, Rect, State);
  s := TStringGrid(Sender).Cells[ACol, ARow];
  if s = 'PAUSED' then
  begin
    TStringGrid(Sender).canvas.Brush.Color := clred;
    TStringGrid(Sender).canvas.fillrect(Rect);
    DrawText((Sender as TStringGrid).canvas.Handle, Pchar(s), Length(s), Rect, dt_wordbreak or DT_CENTER);
  end;
end;

procedure TfrmCageTournament.stg_TournamentsKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  frmMain.SearchStringGrid(stg_Players, frmMain.GetCharFromVirtualKey(Key));
end;

procedure TfrmCageTournament.stg_TournamentsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
  TournamentId, DisplayTableZoneId: string;
begin
  if ARow > 1 then
  begin
    TournamentId := stg_Tournaments.Cells[0, ARow];
    DisplayTableZoneId := stg_Tournaments.Cells[21, ARow];
    frmMain.GetGridData(stg_TableOcupation, '', false);
    frmMain.GetGridData(stg_Players, '', false);
    img_Player.Picture := nil;
    if TournamentId <> '' then
    begin
      if m_FrmDisplay <> nil then
      begin
        if DisplayTableZoneId <> '' then
        begin
          m_FrmDisplay.m_DisplayTableZone := DisplayTableZoneId;
          m_FrmDisplay.m_TournamentID := TournamentId;
        end
        else
        begin
          m_FrmDisplay.m_DisplayTableZone := '-1';
          m_FrmDisplay.m_TournamentID := TournamentId;
        end;
        m_FrmDisplay.TimerChangeScreen.Interval := 1;
        m_FrmDisplay.TimerChangeScreen.Enabled := false;
        m_FrmDisplay.TimerChangeScreen.Enabled := True;
      end;
      frmMain.GetGridData(stg_TableOcupation, 'select t.id, (t.seats)-NVL(Playing,0) as seats_free,t.seats, t.name  from TOURNAMENT_TABLES tt' + ' left join tables t on tt.TABLE_ID = t.ID' +
          ' left join (select * from tickets where TOURNAMENT_ID=' + TournamentId + ' and deleted=0) ti on ti.TABLE_ID=t.ID' +
          ' left join GET_PLAYERS_PLAY_TICK_BY_TABLE gppt on (gppt.table_id=tt.table_id and gppt.tournament_id=tt.tournament_id)' + ' where tt.TOURNAMENT_ID = ' + TournamentId +
          ' group by t.seats,playing,t.name, t.id, t.seats order by name', false);
      stg_TableOcupation.Cells[1, 1] := _('Free') + #13#10 + SumColGridData(stg_TableOcupation, 1, 2, stg_TableOcupation.RowCount);
      stg_TableOcupation.Cells[2, 1] := _('Seats') + #13#10 + SumColGridData(stg_TableOcupation, 2, 2, stg_TableOcupation.RowCount);
      stg_TableOcupation.ColWidths[1] := stg_TableOcupation.width div 3;
      stg_TableOcupation.ColWidths[2] := stg_TableOcupation.width div 3;
      stg_TableOcupation.ColWidths[3] := stg_TableOcupation.width div 3;
      GetTicketsData(TournamentId, stg_TableOcupation.Cells[0, stg_TableOcupation.Row]);
      lbl_TournamentName.Caption := _('Tournament:') + ' ' + stg_Tournaments.Cells[5, ARow];
      // ---------------
    end;
  end
  else
  begin
    ClearStringGrid(stg_TableOcupation);
    ClearStringGrid(stg_Players);
  end;
end;

procedure TfrmCageTournament.tmr_RefreshTimeTimer(Sender: TObject);
var
  NowValue: string;
  DateValue: TDateTime;
begin
  if (frmMain.OracleSession1.CheckConnection(false) <> ccError) and (frmMain.pgc_Main.ActivePage = frmMain.tbs_CageTournament) then
  begin
    NowValue := uUtils.GetFormatedStringDateNOW(frmMain.OracleSession1);
    DateValue := StrToDateTime(NowValue);
    lbl_date.Caption := FormatDateTime('dddd dd.MM.yyyy', DateValue);
    lbl_time.Caption := FormatDateTime('hh:nn', DateValue);
    // dtp_DateChange(self);
  end;
end;

procedure TfrmCageTournament.GetTicketsData(TournamentId: string; TableId: string = '');
var
  OrderAddon, OrderRebuy, OrderWinPay: Boolean;
  WhereCond, OrderBy, Query: string;
begin
  frmMain.GetGridData(stg_Players, '', false);
  if TournamentId <> '' then
  begin
    if (TableId <> '') and (not chb_ShowFromAllTables.Checked) then
    begin
      WhereCond := ' and table_id=' + TableId;
    end
    else
    begin
      WhereCond := '';
    end;
    OrderAddon := false;
    OrderRebuy := false;
    OrderWinPay := false;
    OrderBy := ' order by DATETIME DESC ';
    frmMain.OracleQuery1.Close;
    frmMain.OracleQuery1.SQL.Text := 'SELECT count(0) FROM TICKET_REBUY WHERE VALUE IS NULL AND TOURNAMENT_ID=' + TournamentId;
    frmMain.OracleQuery1.Execute;
    if frmMain.OracleQuery1.Field(0) <> '0' then
    begin
      OrderRebuy := True;
    end;
    frmMain.OracleQuery1.Close;
    frmMain.OracleQuery1.SQL.Text := 'SELECT count(0) FROM TICKET_ADDON WHERE VALUE IS NULL AND TOURNAMENT_ID=' + TournamentId;
    frmMain.OracleQuery1.Execute;
    if frmMain.OracleQuery1.Field(0) <> '0' then
    begin
      OrderAddon := True;
    end;
    frmMain.OracleQuery1.Close;
    frmMain.OracleQuery1.SQL.Text := 'SELECT count(0) FROM TICKETS WHERE WIN_POSITION IS NOT NULL AND PAY_VALUE IS NULL AND TOURNAMENT_ID=' + TournamentId;
    frmMain.OracleQuery1.Execute;
    if frmMain.OracleQuery1.Field(0) <> '0' then
    begin
      OrderWinPay := True;
    end;
    if OrderRebuy or OrderAddon then
    begin
      if OrderWinPay then
      begin
        OrderBy := ' order by DO_ADDON_ID ASC, DO_REBUY_ID ASC, WIN_POSITION ASC NULLS FIRST';
      end
      else
      begin
        OrderBy := ' order by DO_ADDON_ID ASC, DO_REBUY_ID ASC';
      end;
    end
    else if OrderWinPay then
    begin
      OrderBy := ' order by WIN_POSITION ASC NULLS FIRST';
    end;
    Query := (SQL_TicketsGroupPlayers + TournamentId + WhereCond + OrderBy);
    frmMain.GetGridData(stg_Players, Query, false);
    stg_Players.ColWidths[1] := 130;
    stg_Players.ColWidths[2] := -1; // PLAYERID
    stg_Players.ColWidths[3] := -1; // BIRTHDATE
    stg_Players.ColWidths[4] := 35;
    stg_Players.ColWidths[5] := 35;
    stg_Players.ColWidths[6] := 35; // count rebuys
    stg_Players.ColWidths[7] := 35; // COUNT ADDONS
    stg_Players.ColWidths[8] := 120;
    stg_Players.ColWidths[9] := 60;
    stg_Players.ColWidths[10] := 40; // win position
    stg_Players.ColWidths[11] := 60; // pay value
    stg_Players.ColWidths[12] := -1; // table id
    stg_Players.ColWidths[13] := -1; // do rebuy id from table
    stg_Players.ColWidths[14] := -1; // do addon id from table
    stg_Players.ColWidths[15] := 40; // PLAYER POINTS
    stg_Players.Cells[6, 1] := stg_Players.Cells[6, 1] + #13#10 + SumColGridData(stg_Players, 6, 2, stg_Players.RowCount);
    stg_Players.Cells[7, 1] := stg_Players.Cells[7, 1] + #13#10 + SumColGridData(stg_Players, 7, 2, stg_Players.RowCount);
  end;
end;

procedure TfrmCageTournament.img_CashierClick(Sender: TObject);
var
  UserID: string;
begin
  UserID := TImage(Sender).Hint;
  if UserID = '' then // sender is player status label
  begin
    UserID := TImagePanel(TLabel(Sender).Parent).Image.Hint;
  end;
  if UserID = '' then
    UserID := '-1';
  // check if inspector is looged in
  frmMain.OracleQuery1.SQL.Clear;
  frmMain.OracleQuery1.SQL.Text := 'SELECT * FROM CAGE_LOGINS WHERE IN_DATETIME IS NOT NULL AND OUT_DATETIME IS NULL AND USER_ID=' + UserID;
  frmMain.OracleQuery1.Execute;
  if frmMain.OracleQuery1.Eof then
  begin
    // login inspector
    FrmDealerSelect.ShowDealerForm('', '', '', '', UserID, True);
    frmMain.SendEventToServer(EventTypeCashierChange, '', '');
    GetLoggedCahiers();
  end
  else
  begin
    // logout inspector
    if MessageDlg(_('Cashier out?') + '(' + TImagePanel(TLabel(Sender).Parent).PlayerName.Caption + ')', mtWarning, [mbYes, mbNo], 0) = mrYes then
    begin
      UpdateDataToDB('CAGE_LOGINS', 'OUT_DATETIME=(SELECT SYSDATE FROM DUAL)', 'OUT_DATETIME IS NULL AND USER_ID=' + UserID);
      frmMain.SendEventToServer(EventTypeCashierChange, '', '');
      GetLoggedCahiers();
    end;
  end;
end;

procedure TfrmCageTournament.GetLoggedCahiers();
var
  i: Integer;
begin
  if FrmSubjectImage = nil then
    FrmSubjectImage := TFrmSubjectImage.Create(self);
  for i := ComponentCount - 1 downto 0 do
  begin
    if Components[i] is TImagePanel then
    begin
      TImagePanel(Components[i]).Image.Picture := img_Inspector.Picture;
      TImagePanel(Components[i]).Image.OnClick := img_CashierClick; ;
      TImagePanel(Components[i]).PlayerStatus.OnClick := img_CashierClick;
      TImagePanel(Components[i]).PlayerName.OnClick := img_CashierClick;
      TImagePanel(Components[i]).Caption := '';
      TImagePanel(Components[i]).PlayerName.Caption := '';
      TImagePanel(Components[i]).Image.Hint := '';
    end;
  end;
  frmMain.OracleQuery1.Session := OraSessMainUtils;
  frmMain.OracleQuery1.Close;
  frmMain.OracleQuery1.SQL.Clear;
  frmMain.OracleQuery1.SQL.Text := ('SELECT * FROM GET_LOGGED_CASHIERS');
  frmMain.OracleQuery1.Execute;
  img_Cashier.Image.Picture := img_Inspector.Picture;
  if not frmMain.OracleQuery1.Eof then
  begin
    img_Cashier.PlayerName.Caption := VarToStr(frmMain.OracleQuery1.Field('SUBJECT'));
    FrmSubjectImage.img_TakenPhoto.Picture.Assign(uUtils.GetImage(SQL_User_Picture + VarToStr(frmMain.OracleQuery1.Field('USER_ID')), OraSessMainUtils, false));
    FrmSubjectImage.img_BlackHole.BringToFront;
    img_Cashier.Image.Transparent := True;
    img_Cashier.Image.Picture.Bitmap.Assign(FrmSubjectImage.GetFormImage);
    img_Cashier.Image.Picture.Bitmap.PixelFormat := pf24Bit;
    img_Cashier.Image.Hint := VarToStr(frmMain.OracleQuery1.Field('USER_ID'));
  end;
end;

procedure TfrmCageTournament.btn_CancelOperationClick(Sender: TObject);
begin
  if (stg_Players.Row > 1) and (stg_Players.Cells[0, stg_Players.Row] <> '') then
  begin
    FrmCancelOperation.ShowForm(stg_Players.Cells[0, stg_Players.Row], stg_Players.Cells[1, stg_Players.Row], false, false);
    dtp_DateChange(self);
  end;
end;

procedure TfrmCageTournament.btn_PlayerOutClick(Sender: TObject);
begin
  FrmPlayerOut.ShowModal;
  stg_TournamentsSelectCell(self, 0, stg_Tournaments.Row, CanSelect);
  dtp_DateChange(self);
end;

procedure TfrmCageTournament.btn_PlayerWinnerClick(Sender: TObject);
begin
  FrmPlayerWin.ShowWinPlayerForm(stg_Tournaments.Cells[0, stg_Tournaments.Row], stg_Players.Cells[0, stg_Players.Row], stg_Players.Cells[10, stg_Players.Row]);
  stg_TournamentsSelectCell(self, 0, stg_Tournaments.Row, CanSelect);
  dtp_DateChange(self);
end;

procedure TfrmCageTournament.btn_ReprintClick(Sender: TObject);
begin
  if (stg_Players.Row > 1) and (stg_Players.Cells[0, stg_Players.Row] <> '') then
  begin
    FrmCancelOperation.ShowForm(stg_Players.Cells[0, stg_Players.Row], stg_Players.Cells[1, stg_Players.Row], True, false);
  end;
end;

procedure TfrmCageTournament.btn_ShowBigClockClick(Sender: TObject);
begin
  FrmDisplay := TFrmDisplay.Create(self);
  FrmDisplay.m_DisplayTableZone := stg_Tournaments.Cells[21, stg_Tournaments.Row];
  FrmDisplay.m_TournamentID := stg_Tournaments.Cells[0, stg_Tournaments.Row];
  FrmDisplay.Show;
end;

procedure TfrmCageTournament.btn_TodayClick(Sender: TObject);
begin
  dtp_Date.Date := now();
  dtp_DateChange(self);
end;

procedure TfrmCageTournament.chb_ShowFromAllTablesClick(Sender: TObject);
begin
  if (stg_TableOcupation.Row > 1) and (stg_Tournaments.Row > 1) then
  begin
    GetTicketsData(stg_Tournaments.Cells[0, stg_Tournaments.Row], stg_TableOcupation.Cells[0, stg_TableOcupation.Row]);
  end;
end;

procedure TfrmCageTournament.chb_ShowOlderClick(Sender: TObject);
begin
  FrmLoading.Show;
  FrmLoading.ProgressBar1.Position := 50;
  FrmLoading.Repaint;
  dtp_DateChange(self);
  FrmLoading.Close;
end;

procedure TfrmCageTournament.com_OrderTicketsByChange(Sender: TObject);
begin
  GetTicketsData(stg_Tournaments.Cells[0, stg_Tournaments.Row], stg_TableOcupation.Cells[0, stg_TableOcupation.Row]);
end;

procedure TfrmCageTournament.com_ShowFinishedClick(Sender: TObject);
begin
  dtp_DateChange(self);
end;

procedure TfrmCageTournament.dtp_DateChange(Sender: TObject);
var
  WhereCond, Query, Finished1, Finished2, NotArchived: string;
  SelRowTou, SelRowTicket: Integer;
begin
  LockWindowUpdate(self.Handle);
  NotArchived := '';
  if com_ShowFinished.Checked then
  begin
    Finished1 := '';
    Finished2 := ' OR STATUS=''FINISHED''';
  end
  else
  begin
    Finished1 := ' (NVL(PAID_WINS,0)<NVL(WIN_TO_NUM,0) AND NVL(PAID_WINS,0)<>NVL(TICKET_COUNT,0)) OR';
    Finished2 := ' AND STATUS<>''FINISHED''';
  end;
  if Trunc(dtp_Date.Date) = Trunc(now()) then
  begin
    com_ShowFinished.Visible := True;
    NotArchived := ' ARCHIVE=0 AND ';
    WhereCond := 'where ' + NotArchived + Finished1 + ' (event_start>=(select GD_START from GET_GD_START_TIME)) AND ' + NotArchived + ' (EVENT_END_LONG>(SELECT SYSDATE FROM DUAL) ' + Finished2 + ')';
  end
  else
  begin
    com_ShowFinished.Visible := false;
    WhereCond := 'where ' + Finished1 + '''' + DateToStr(dtp_Date.Date) + '''' + ' between trunc(event_start) AND trunc(event_end_long) ';
  end;
  Query := 'SELECT * FROM GETTICKETTOURNAMENTS GTT LEFT JOIN (SELECT COUNT(0) AS PAID_WINS, TOURNAMENT_ID FROM TICKETS WHERE ' + NotArchived +
    ' DELETED=0 GROUP BY TOURNAMENT_ID) TI ON TI.TOURNAMENT_ID=GTT.ID ' + WhereCond + ' order by trunc(event_start) ASC, TIME ASC';
  SelRowTou := stg_Tournaments.Row;
  SelRowTicket := stg_Players.Row;
  if SelRowTou < 2 then
    SelRowTou := 2;
  frmMain.GetGridData(stg_Tournaments, Query, false);
  frmMain.SelectGridRow(stg_Tournaments, SelRowTou);
  stg_TournamentsSelectCell(self, 0, SelRowTou, CanSelect);
  stg_Tournaments.ColWidths[1] := -1; // rebuy allow
  stg_Tournaments.ColWidths[2] := -1; // addon allow
  stg_Tournaments.ColWidths[3] := 40;
  stg_Tournaments.ColWidths[4] := 75;
  stg_Tournaments.ColWidths[5] := 130;
  stg_Tournaments.ColWidths[6] := 50;
  stg_Tournaments.ColWidths[7] := 80;
  stg_Tournaments.ColWidths[8] := 70;
  stg_Tournaments.ColWidths[9] := 50;
  stg_Tournaments.ColWidths[10] := 50;
  stg_Tournaments.ColWidths[11] := -1;
  stg_Tournaments.ColWidths[12] := -1; // is stopped
  stg_Tournaments.ColWidths[13] := 90; // STATUS
  stg_Tournaments.ColWidths[14] := 100;
  stg_Tournaments.ColWidths[15] := 50; // END_TIME
  stg_Tournaments.ColWidths[16] := -1; // WIN TO PLAYER NUMBER
  stg_Tournaments.ColWidths[17] := -1; // ARCHIVE
  stg_Tournaments.ColWidths[18] := -1; // FREE POS
  stg_Tournaments.ColWidths[19] := -1; // EVENT END LONG
  stg_Tournaments.ColWidths[20] := -1; // ticket count
  stg_Tournaments.ColWidths[21] := -1; // display zone id
  stg_Tournaments.ColWidths[22] := -1; // payed wins count
  stg_Tournaments.ColWidths[23] := -1; // tournament_id finished
  frmMain.SelectGridRow(stg_Players, SelRowTicket);
  stg_PlayersSelectCell(self, 0, SelRowTicket, CanSelect);
  LockWindowUpdate(0);
end;

procedure TfrmCageTournament.FormCreate(Sender: TObject);
begin
  lbl_TournamentName.Caption := '';
  lbl_date.Caption := '';
  lbl_time.Caption := '';
  dtp_Date.Date := now();
  m_FrmDisplay := TFrmDisplay.Create(self);
  m_FrmDisplay.Parent := pnl_Clock;
  m_FrmDisplay.BorderStyle := BSnONE;
  m_FrmDisplay.Align := ALcLIENT;
  m_FrmDisplay.Show;
  img_Cashier.Image.OnClick := img_CashierClick;
  img_Cashier.PlayerStatus.OnClick := img_CashierClick;
  img_Cashier.PlayerName.OnClick := img_CashierClick;
end;

procedure TfrmCageTournament.btn_PauseContinueClick(Sender: TObject);
var
  NewStatus, DtTime, TournamentId: string;
  Running: Boolean;
begin
  if (stg_Tournaments.Cells[13, stg_Tournaments.Row] = 'PAUSED') then
  begin
    NewStatus := 'RUNNING'
  end
  else
  begin
    NewStatus := 'PAUSED';
  end;
  if MessageDlg(_('Change tournament to: ') + NewStatus, mtConfirmation, [mbYes, mbNo], 0) = mrYes then
  begin
    DtTime := 'to_date(''' + GetFormatedStringDateNOW(frmMain.OracleSession1) + ''', ''dd.mm.yyyy hh24:mi:ss'')';
    TournamentId := stg_Tournaments.Cells[0, stg_Tournaments.Row];
    // -------
    if TournamentId <> '' then
    begin
      frmMain.OracleQuery1.SQL.Clear;
      frmMain.OracleQuery1.SQL.Text := (SQL_IsRunningTournamentID + ' AND TOURNAMENT_ID=' + TournamentId);
      frmMain.OracleQuery1.Execute;
      Running := frmMain.OracleQuery1.Eof;
      // ----------
      if Running then
      begin
        InsertDataIntoDB('TOURNAMENT_STOPS', 'TOURNAMENT_ID, STOP_FROM, STOP_TO', TournamentId + ',' + DtTime + ',' + '''' + '''');
      end
      else
      begin
        UpdateDataToDB('TOURNAMENT_STOPS', 'STOP_TO=' + DtTime, 'STOP_TO IS NULL AND TOURNAMENT_ID=' + TournamentId);
      end;
      dtp_DateChange(self);
    end;
  end;
end;

end.
